package com.zerui.manager.app.deviceTouchSync;

import com.zerui.authority.context.LoginUserHolder;
import com.zerui.cola.dto.Response;
import com.zerui.cola.dto.SingleResponse;
import com.zerui.manager.app.deviceTouchSync.executer.DeviceTouchSyncAddCmdExe;
import com.zerui.manager.app.deviceTouchSync.executer.DeviceTouchSyncDelCmdExe;
import com.zerui.manager.app.scheduler.bean.JobBean;
import com.zerui.manager.app.scheduler.bean.JobConst;
import com.zerui.manager.app.scheduler.utils.ScheduleUtils;
import com.zerui.manager.web.DeviceTouchSyncService;
import com.zerui.manager.web.cmd.DeviceTouchSyncAddCmd;
import com.zerui.manager.web.enums.DeviceFromEnum;
import com.zerui.manager.web.enums.DeviceSyncStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备服务实现类
 *
 * @author pyzhang
 * @since 2024-04-11
 */
@Slf4j
@Service
public class DeviceTouchSyncServiceImpl implements DeviceTouchSyncService {
    @Resource
    private DeviceTouchSyncAddCmdExe deviceTouchSyncAddCmdExe;
    @Resource
    private DeviceTouchSyncDelCmdExe deviceTouchSyncDelCmdExe;
    @Resource
    private Scheduler scheduler;

    @Override
    public Response syncData(List<Integer> froms) {
        for (Integer from : froms) {
            DeviceTouchSyncAddCmd addCmd = new DeviceTouchSyncAddCmd();
            addCmd.setSyncTime(LocalDateTime.now());
            addCmd.setSyncFrom(from);
            addCmd.setSyncRemark("从【" + DeviceFromEnum.getLabel(from) + "】同步门禁设备");
            addCmd.setSyncOperator(LoginUserHolder.get().getUsername()); // 登录用户
            addCmd.setSyncStatus(DeviceSyncStatusEnum.SYNC_INIT.getCode());
            JobBean jobBean = deviceTouchSyncAddCmdExe.execute(addCmd);
            try {
                ScheduleUtils.createScheduleJob(scheduler, jobBean);
                ScheduleUtils.executeJob(scheduler, jobBean.getJobId(), JobConst.GROUP_DEVICE_TOUCH); // 开始执行
            } catch (Exception e) {
                deviceTouchSyncDelCmdExe.deleteById(jobBean.getJobId());
                log.error("从【" + DeviceFromEnum.getLabel(from) + "】同步门禁设备出错", e);
            }
        }
        return SingleResponse.buildSuccess();
    }
}
